import { ElMessage, ElMessageBox } from "element-plus";
import { useAuthStore } from "@/store";
import { useRouterStore } from "@/store";

let isConfirming = false;
export function resolveResError(code: number, message: string) {
  const { route } = useRouterStore();

  switch (code) {
    case 401:
      if (isConfirming) return;
      isConfirming = true;

      setTimeout(() => {
        if (route.name == "Login") return;
        ElMessageBox.confirm("登录已过期，是否重新登录？", "提示")
          .then(() => {
            useAuthStore().logout();
            ElMessage.success("已退出登录");
            isConfirming = false;
          })
          .catch(() => {
            isConfirming = false;
          });
      }, 600);
      return false;
    case 402: {
      if (isConfirming) return;
      isConfirming = true;
      if (route.name == "Login") return;

      ElMessageBox.confirm("当前账号已经在别的地方登录！", "提示")
        .then(() => {
          useAuthStore().logout();
          ElMessage.success("已退出登录");
          isConfirming = false;
        })
        .catch(() => {
          useAuthStore().logout();
          ElMessage.success("已退出登录");
          isConfirming = false;
        });

      return false;
    }
    case 403:
      message = message || "请求被拒绝";
      break;
    case 404:
      message = "请求资源或接口不存在";
      break;
    case 500:
      message = "服务器发生异常";
      break;
    default:
      message = message ?? `【${code}】: 未知异常!`;
      break;
  }

  return message;
}
